package logic

import (
	"context"
	"encoding/json"

	"lottery-zero/internal/model"
	"lottery-zero/internal/svc"
	"lottery-zero/internal/types"

	"github.com/tal-tech/go-zero/core/logx"
)

type SsqgetforeverbetLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewSsqgetforeverbetLogic(ctx context.Context, svcCtx *svc.ServiceContext) SsqgetforeverbetLogic {
	return SsqgetforeverbetLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *SsqgetforeverbetLogic) Ssqgetforeverbet(req types.SsqTicksForeverPageReq, userId string) (*types.SsqTicksPageReply, error) {
	userInt, _ := json.Number(userId).Int64()
	tx := l.svcCtx.PGDB.Model(&model.UserDoubleBallForever{}).Where("user_id = ?", userInt)
	var (
		total     int64
		pageCount int64
		page      int64
	)
	tx.Count(&total)

	// 计算 page count
	pageCount = total / req.PageSize
	if total%req.PageSize > 0 {
		pageCount += 1
	}

	// 计算page
	if req.Page == 0 {
		page = 1
	} else if req.Page > pageCount {
		page = pageCount
	} else {
		page = req.Page
	}

	// 获取分页后的内容
	fubs := []model.UserDoubleBallForever{}
	tx.Limit(int(req.PageSize)).Offset(int((page - 1) * req.PageSize)).Find(&fubs)

	return &types.SsqTicksPageReply{Page: page,
		PageSize:  req.PageSize,
		Total:     total,
		PageCount: pageCount,
		Data:      fubs,
	}, nil
}
